# alembic/env.py
import os
import sys
from logging.config import fileConfig
from sqlalchemy import pool
from sqlalchemy.engine import create_engine
from alembic import context

sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))

from backend.db.base import Base
from backend.core.config import settings

config = context.config

# 使用同步数据库 URL
DATABASE_SYNC_URL = settings.DATABASE_SYNC_URL

target_metadata = Base.metadata


def run_migrations_online():
    connectable = create_engine(
        DATABASE_SYNC_URL,
        poolclass=pool.NullPool,
    )

    with connectable.connect() as connection:
        # 直接运行迁移，不检查表是否存在
        context.configure(
            connection=connection,
            target_metadata=target_metadata,
            compare_type=True,
            compare_server_default=True,
            render_as_batch=True,
        )

        with context.begin_transaction():
            context.run_migrations()


if context.is_offline_mode():
    raise NotImplementedError("Offline mode not supported")
else:
    run_migrations_online()